/*
 * key.c
 * Copyright (C) 2020 kalipy <kalipy@debian>
 *
 * Distributed under terms of the MIT license.
 */

#include "key.h"
#include "los_sys.h"
#include "los_base.h"
#include "los_task.h"
#include "los_tick.h"

void drv_key_init(void)
{
    //使能gpiof
    RCC->AHB1ENR |= 1<<5;

    //GPIOF.9 key0
    GPIOF->MODER &= ~(3<<(9*2));//清零
    GPIOF->MODER |= (0<<(9*2));//输入模式
    GPIOF->PUPDR &= ~(3<<(9*2));//清零
    GPIOF->PUPDR |= (1<<(9*2));//上拉

    //GPIOF.8 key1
    GPIOF->MODER &= ~(3<<(8*2));//清零
    GPIOF->MODER |= (0<<(8*2));//输入模式
    GPIOF->PUPDR &= ~(3<<(8*2));//清零
    GPIOF->PUPDR |= (1<<(8*2));//上拉

    //GPIOF.7 key2
    GPIOF->MODER &= ~(3<<(7*2));//清零
    GPIOF->MODER |= (0<<(7*2));//输入模式
    GPIOF->PUPDR &= ~(3<<(7*2));//清零
    GPIOF->PUPDR |= (1<<(7*2));//上拉

    //GPIOF.6 key3
    GPIOF->MODER &= ~(3<<(6*2));//清零
    GPIOF->MODER |= (0<<(6*2));//输入模式
    GPIOF->PUPDR &= ~(3<<(6*2));//清零
    GPIOF->PUPDR |= (1<<(6*2));//上拉
}

int drv_get_key_pin_value(int keyx_pin)
{
    GPIOF->IDR &= (0x0000ffff);//清除高16位
    if ((GPIOF->IDR & (1<<keyx_pin)) == 0)
    {
        return 0;
    } else {
        return 1;
    }
}

//获取当前按键状态(不支持连续按)：
//-1，没有任何按键按下
//0，KEY0按下
//1，KEY1按下
//2，KEY2按下
//3，KEY3按下
int drv_get_key(void)
{
	static int key_up=1;//按键按松开标志
	if(key_up&&(KEY0==0||KEY1==0||KEY2==0||KEY3==0))//按键被按下
	{
        LOS_TaskDelay(20);
		//delay_ms(10);//去抖动
		key_up=0;
		if(KEY0==0)return 0;
		else if(KEY1==0)return 1;
		else if(KEY2==0)return 2;
		else if(KEY3==0)return 3;
	}else if(KEY0==1&&KEY1==1&&KEY2==1&&KEY3==1)key_up=1;
 	return -1;// 无按键按下
}

//获取当前按键状态(支持连续按)：
int drv_get_key_hold(void)
{
	if(KEY0==0||KEY1==0||KEY2==0||KEY3==0)//按键被按下
    {
        LOS_TaskDelay(20);
        //delay_ms(10);//去抖动
        if(KEY1==0)return 0;//确实被按下
        else if(KEY1==0)return 1;
        else if(KEY2==0)return 2;
        else if(KEY3==0)return 3;
    }
    return -1;// 无按键按下
}

